package org.hcyspartnoc.demo.utils;


import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.hcyspartnoc.demo.common.core.configuration.UserConfiguration;
import org.hcyspartnoc.demo.common.core.constant.HttpStatus;
import org.hcyspartnoc.demo.common.exception.framework.AuthException;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;

@Component
public class RequestUtil {
    private static UserConfiguration userConfiguration;
    @Resource
    public void setUserConfiguration(UserConfiguration userConfiguration) {
        RequestUtil.userConfiguration = userConfiguration;
    }

    //获取HttpServletRequest
    public static HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    public static String getToken() throws AuthException {
        String authorization = getHttpServletRequest().getHeader("Authorization");
        if (Objects.isNull(authorization))//token格式错误
            throw new AuthException(AuthException.TOKEN_FORMAT_WRONG, HttpStatus.FORBIDDEN);
        String[] temp = authorization.split(" ");
        /*校验token*/
        if (temp.length != 2 || !temp[0].equals(userConfiguration.getTokenPrefix()))//token格式验证
            throw new AuthException(AuthException.TOKEN_FORMAT_WRONG, HttpStatus.FORBIDDEN);
        String token = temp[1];
        if (token == null || token.isEmpty())//token非空验证
            throw new AuthException(AuthException.PERMISSION_FAILED, HttpStatus.FORBIDDEN);
        return token;
    }

    //获取ip
    public static String getIp() {
        HttpServletRequest request = getHttpServletRequest();
        String ip = request.getHeader("x-forwarded-for");
        // 如果X-Forwarded-For包含多个IP（可能经过多个代理），只取第一个
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0];
        }
        String unknown = "unknown";
        if (ip == null || ip.isEmpty() || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.isEmpty() || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.isEmpty() || unknown.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
